<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '考试详情',
    navigationStyle: 'custom',
  },
}
</route>
<!--考场-->
<template>
  <view class="exam-container">
    <!-- 滚动内容区域 (div1) -->
    <scroll-view
      class="content-scroll"
      scroll-y
      :style="{ height: pageData.contentScrollHeight + 'px' }"
    >
      <image
        style="z-index: -10; position: absolute; top: 0; width: 100vw; height: 100vh"
        :src="examBg"
        mode="widthFix"
      />

      <!-- 考试标题 -->
      <view class="exam-header">
        <view class="exam-title">答题详情</view>
      </view>

      <!-- 题型和操作区域 -->
      <view class="question-type-row">
        <view class="question-type" style="margin-left: 30rpx">
          <image src="/static/images/icons/exam/icon_questionMark.png" class="type-icon"></image>
          <text class="type-text">
            {{
              pageData.questionList[pageData.currentQuestion].qType === 1
                ? '主观题'
                : pageData.questionList[pageData.currentQuestion].qType === 2
                  ? '单选题'
                  : pageData.questionList[pageData.currentQuestion].qType === 3
                    ? '多选题'
                    : pageData.questionList[pageData.currentQuestion].qType === 4
                      ? '判断题'
                      : pageData.questionList[pageData.currentQuestion].qTypeShow
            }}
          </text>
        </view>
        <view style="margin-right: 40rpx; display: flex">
          <view class="do-button-group" style="margin-right: 10rpx" @click="exitExam">退出</view>
        </view>
      </view>

      <!-- 题目内容 -->
      <view class="question-content">
        <view class="question-text">
          <rich-text :nodes="currentQuestionData.questionContent"></rich-text>
          <text class="question-score">({{ currentQuestionData.score }}分)</text>
        </view>

        <view class="divider"></view>
        <!-- 选项列表 - 单选 -->
        <view v-if="currentQuestionData.qType === 2" class="options-list">
          <view
            v-for="(option, index) in currentQuestionData.questionAnswer"
            :key="option.optionId"
            class="option-item"
            :class="{ selected: isOptionSelected(option.optionId) }"
          >
            <view class="option-circle">{{ option.orderShow }}</view>
            <view class="option-text">
              <rich-text :nodes="option.answerContent"></rich-text>
            </view>
          </view>
        </view>

        <!-- 选项列表 - 多选 -->
        <view v-else-if="currentQuestionData.qType === 3" class="options-list">
          <view
            v-for="(option, index) in currentQuestionData.questionAnswer"
            :key="option.optionId"
            class="option-item"
            :class="{ selected: isOptionSelected(option.optionId) }"
          >
            <view class="option-circle">{{ option.orderShow }}</view>
            <view class="option-text">
              <rich-text :nodes="option.answerContent"></rich-text>
            </view>
          </view>
        </view>

        <!-- 主观题 -->
        <view v-else-if="currentQuestionData.qType === 1" class="subjective-answer">
          <textarea
            v-model="pageData.userAnswers[pageData.currentQuestion][0]"
            class="subjective-textarea"
            placeholder="请输入您的答案"
            disabled
          ></textarea>
        </view>

        <!-- 判断题 -->
        <view v-else-if="currentQuestionData.qType === 4" class="options-list">
          <view
            class="option-item"
            :class="{
              selected:
                Array.isArray(pageData.userAnswers[pageData.currentQuestion]) &&
                pageData.userAnswers[pageData.currentQuestion].includes('1'),
            }"
          >
            <view class="option-circle">A</view>
            <text class="option-text">正确</text>
          </view>
          <view
            class="option-item"
            :class="{
              selected:
                Array.isArray(pageData.userAnswers[pageData.currentQuestion]) &&
                pageData.userAnswers[pageData.currentQuestion].includes('0'),
            }"
          >
            <view class="option-circle">B</view>
            <text class="option-text">错误</text>
          </view>
        </view>

        <view style="color: #333; margin-top: 40rpx">
          <view
            style="display: flex; align-items: center; color: green"
            v-if="isCorrectAnswer(pageData.currentQuestion)"
          >
            <uni-icons type="checkmarkempty" size="30" color="green"></uni-icons>
            <text>回答正确</text>
          </view>
          <view
            style="display: flex; align-items: center; color: red"
            v-if="!isCorrectAnswer(pageData.currentQuestion)"
          >
            <uni-icons type="closeempty" size="30" color="red"></uni-icons>
            <text>回答错误</text>
          </view>
          <view
            style="display: flex; align-items: center"
            v-if="!isCorrectAnswer(pageData.currentQuestion)"
          >
            正确答案:
            <text style="color: green; margin-left: 10rpx">
              {{ pageData.questionList[pageData.currentQuestion].questionAnswerTrueStr }}
            </text>
          </view>
          <view style="display: flex; align-items: center">
            试题解析:
            <text style="margin-left: 10rpx">
              {{ pageData.questionList[pageData.currentQuestion].questionAnalysis || '暂无' }}
            </text>
          </view>
        </view>
      </view>
      <!-- 底部占位，防止内容被底部导航栏遮挡 -->
      <view class="bottom-placeholder"></view>
    </scroll-view>

    <!-- 底部固定导航 (div2) -->
    <view class="bottom-nav">
      <view class="bottom-nav-content">
        <view class="nav-btn prev-btn" @click="prevQuestion">上一题</view>
        <view class="answer-indicator">
          <image
            src="/static/images/icons/exam/icon_answerSheet.png"
            class="indicator-icon"
          ></image>
          <text class="color-#2873f9" @click="pageData.cardShow = true">答题卡</text>
          <text class="indicator-text">
            {{ pageData.currentQuestion + 1 }}/{{ totalQuestions }}
          </text>
        </view>
        <view class="nav-btn next-btn" @click="nextQuestion">下一题</view>
      </view>
    </view>

    <!-- 答题卡 -->
    <wd-popup
      v-model="pageData.cardShow"
      position="bottom"
      custom-style="border-radius:32rpx;height: 750rpx;"
    >
      <view class="answer-card">
        <!-- 头部区域 -->
        <view class="card-header">
          <view class="card-title">
            <image src="/static/images/icons/exam/icon_answerSheet.png" class="card-icon"></image>
            <text class="card-title-text color-#2873f9">答题卡</text>
            <!-- 筛选按钮 -->
            <view class="filter-buttons">
              <view
                class="filter-btn"
                :class="{ active: pageData.cardFilter === 'all' }"
                @click="setCardFilter('all')"
              >
                全
              </view>
            </view>
            <view class="filter-buttons">
              <view
                class="filter-btn"
                :class="{ active: pageData.cardFilter === 'non' }"
                @click="setCardFilter('non')"
              >
                错
              </view>
            </view>
            <view class="filter-buttons">
              <view
                class="filter-btn"
                :class="{ active: pageData.cardFilter === 'alr' }"
                @click="setCardFilter('alr')"
              >
                正
              </view>
            </view>
          </view>
          <view class="close-btn" @click="pageData.cardShow = false">x</view>
        </view>

        <!-- 题目序号区域 -->
        <view class="question-grid" v-if="pageData.cardFilter === 'all'">
          <view v-for="(item, index) in pageData.questionList" :key="index">
            <view
              class="question-item"
              :class="{
                answered: hasAnswer(index),
              }"
              @click="goToQuestion(index)"
            >
              <text
                :class="{
                  correctAnswer: isCorrectAnswer(index),
                }"
              >
                {{ index + 1 }}
              </text>
            </view>
          </view>
        </view>
        <view class="question-grid" v-if="pageData.cardFilter === 'non'">
          <view v-for="(item, index) in pageData.questionList" :key="index">
            <view
              v-if="!isCorrectAnswer(index)"
              class="question-item"
              :class="{
                answered: hasAnswer(index),
              }"
              @click="goToQuestion(index)"
            >
              <text
                :class="{
                  correctAnswer: isCorrectAnswer(index),
                }"
              >
                {{ index + 1 }}
              </text>
            </view>
          </view>
        </view>
        <view class="question-grid" v-if="pageData.cardFilter === 'alr'">
          <view v-for="(item, index) in pageData.questionList" :key="index">
            <view
              v-if="isCorrectAnswer(index)"
              class="question-item"
              :class="{
                answered: hasAnswer(index),
                hidden: shouldHideQuestion(index),
              }"
              @click="goToQuestion(index)"
            >
              <text
                :class="{
                  correctAnswer: isCorrectAnswer(index),
                }"
              >
                {{ index + 1 }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import {
  getExampaperInformation,
  submitUserAnswer,
  saveUserOneAnswer,
  abandonExamTest,
  ExamQuestion,
} from '@/service/exam/exam'
import { examBg } from '@/static/imgMap'

/**
 * 页面数据统一管理
 */
const pageData = reactive({
  // UI相关
  contentScrollHeight: 500, // 内容区滚动高度，默认值
  showAnswer: false, // 不显示答案

  // 考试基本信息
  examTitle: '在线考试123123123123123', // 考试标题
  examDuration: 30, // 考试时间（分钟）
  remainingTime: 30 * 60, // 剩余时间（秒）

  // 题目数据
  currentQuestion: 0, // 当前题目索引
  // 用户答案记录 userAnswers: [['501'], ['506', '507'], ['hello'], ['1']]
  userAnswers: [],
  questionList: [],
  studentAnswer: [], // 原始答案

  // 答题卡相关
  cardShow: false,
  cardFilter: 'all', // 筛选模式：all(全部)\
  showCommit: false,
  showExit: false,

  // 用户信息
  senduserId: 0, // 从URL获取的用户ID
})

// 计算当前题目的总数
const totalQuestions = computed(() => pageData.questionList.length)

// 计算当前显示的题目数据
const currentQuestionData = computed(() => pageData.questionList[pageData.currentQuestion])

/**
 * 加载试卷信息
 */
const loadExamData = async () => {
  const res = await getExampaperInformation(pageData.senduserId)
  if (res.code === 200 && res.data) {
    // 设置试卷标题
    pageData.examTitle = res.data.exampaperTitle || '在线考试'

    // 加载题目列表
    pageData.questionList = res.data.questionList || []
    // 将 res.data.studentAnswer 转化成这样的格式 userAnswers: [['501'], ['506', '507'], ['hello'], ['1']]
    // 将 res.data.studentAnswer 转化为所需的格式
    pageData.studentAnswer = res.data.studentAnswer || []
    pageData.userAnswers = res.data.studentAnswer.reduce((result, item) => {
      // 创建一个映射，以问题ID为键
      result[pageData.questionList.findIndex((q) => q.questionID === item.qid)] = item.answer || []
      return result
    }, {})

    // 确保所有题目都有一个对应的答案数组（即使是空的）
    pageData.questionList.forEach((question, index) => {
      if (!pageData.userAnswers[index]) {
        pageData.userAnswers[index] = []
      }
    })

    console.log('试卷数据加载成功', pageData.questionList)
  } else {
    uni.showToast({
      title: res.message || '获取考试信息失败',
      icon: 'none',
    })
  }
}

/**
 * 判断选项是否被选中
 * @param {string} optionId - 选项ID
 * @returns {boolean} - 是否被选中
 */
const isOptionSelected = (optionId) => {
  const currentAnswers = pageData.userAnswers[pageData.currentQuestion]
  if (!currentAnswers) return false
  return currentAnswers.includes(optionId.toString())
}

/**
 * 上一题
 */
const prevQuestion = async () => {
  if (pageData.currentQuestion > 0) {
    pageData.currentQuestion--
  }
}

/**
 * 下一题
 */
const nextQuestion = async () => {
  // 切换到下一题
  if (pageData.currentQuestion < totalQuestions.value - 1) {
    pageData.currentQuestion++
  }
}

/**
 * 退出考试
 */
const exitExam = async () => {
  // 返回上一页
  uni.navigateBack()
}

/**
 * 设置答题卡筛选模式
 * @param {string} filter - 筛选模式：'all'
 */
const setCardFilter = (filter) => {
  pageData.cardFilter = filter
}

/**
 * 跳转到指定题目
 * @param {number} index - 题目索引
 */
const goToQuestion = (index) => {
  pageData.currentQuestion = index
  pageData.cardShow = false
}

/**
 * 判断题目是否已回答
 * @param {number} index - 题目索引
 * @returns {boolean} - 是否已回答
 */
const hasAnswer = (index) => {
  const answers = pageData.userAnswers[index]
  return (
    answers &&
    ((Array.isArray(answers) && answers.length > 0) ||
      (typeof answers === 'string' && answers.trim() !== ''))
  )
}

/**
 * 判断题目是否正确
 */
const isCorrectAnswer = (index) => {
  return pageData.studentAnswer[index].userScore > 0
}

/**
 * 根据当前筛选模式判断是否应该隐藏题目
 * @param {number} index - 题目索引
 * @returns {boolean} - 是否应该隐藏
 */
const shouldHideQuestion = (index) => {
  // 目前只有全部模式，所以不需要隐藏任何题目
  return false
}

onLoad((option) => {
  // 从URL参数中获取考试ID
  if (option.id) {
    pageData.senduserId = parseInt(option.id)
    // 加载考试数据
    loadExamData()
  } else {
    uni.showToast({
      title: '缺少考试ID参数',
      icon: 'none',
    })
  }
})

// 生命周期钩子 - 组件挂载完成
onMounted(() => {
  // 计算内容区高度
  uni.getSystemInfo({
    success(res) {
      const screenHeight = res.windowHeight

      // 仅需计算底部导航栏的高度
      uni
        .createSelectorQuery()
        .select('.bottom-nav')
        .boundingClientRect((data) => {
          if (data) {
            // 计算内容区高度 = 屏幕高度 - 底部导航栏高度
            pageData.contentScrollHeight = screenHeight - data.height
          }
        })
        .exec()
    },
  })
})
</script>

<style scoped lang="scss">
.correctAnswer {
  border-style: solid;
  border-width: 2px;
  border-color: #5ffb5f;
}
.exam-container {
  width: 750rpx;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  color: #fff;
  position: relative;
}

.commit-confirm {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.6);
  position: absolute;
  z-index: 20;

  .card-confirm {
    width: 600rpx;
    background-color: #fff;
    color: #333;
    display: flex;
    flex-direction: column;
    border-radius: 15rpx;
    padding: 30rpx 30rpx 50rpx;
    box-sizing: border-box;
    align-items: center;
  }

  .confirm-title {
    font-size: 30rpx;
    color: #2725ab;
    text-align: center;
    margin-top: 100rpx;
  }

  .confirm-info {
    display: flex;
    flex-direction: column;
    margin-bottom: 40rpx;
  }

  .info-item {
    display: flex;
    margin-bottom: 30rpx;
  }

  .info-item:first-child {
    margin-top: 70rpx;
  }

  .info-label {
    font-size: 25rpx;
    color: black;
    width: 160rpx;
  }

  .info-value {
    font-size: 25rpx;
    color: black;
  }

  .confirm-text {
    font-size: 30rpx;
    color: #2725ab;
    text-align: center;
    margin-bottom: 40rpx;
  }

  .confirm-buttons {
    display: flex;
    justify-content: space-between;
    margin-top: 70rpx;
  }
  .confirm-buttons-low {
    display: flex;
    justify-content: space-between;
  }

  .cancel-btn,
  .submit-btn {
    width: 240rpx;
    height: 60rpx;
    border-radius: 8rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 32rpx;
  }

  .cancel-btn {
    background-color: #e0e0e0;
    color: #333;
  }

  .submit-btn {
    background-color: #2725ab;
    color: #fff;
  }
}

.answer-card {
  width: 750rpx;
  height: 750rpx;
  padding: 30rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.content-scroll {
  width: 750rpx;
  box-sizing: border-box;

  background-size: cover;
  background-repeat: repeat-y;
}

.exam-header {
  width: 750rpx;
  padding: 40rpx 0;
  margin-top: 40rpx;
  margin-bottom: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.exam-title {
  margin-top: 20rpx;
  width: 690rpx;
  font-size: 36rpx;
  text-align: center;
  line-height: 40rpx;
}

.timer-section {
  width: 750rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
}

.timer {
  margin-top: 20rpx;
  margin-left: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.timer-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 10rpx;
}

.timer-text {
  font-size: 32rpx;
}

.question-type-row {
  width: 750rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.question-type {
  display: flex;
  align-items: center;
}

.type-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}

.type-text {
  font-size: 32rpx;
}

.action-buttons {
  display: flex;
  align-items: center;
}

.exit-btn,
.submit-btn {
  width: 160rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 28rpx;
  text-align: center;
  border-radius: 30rpx;
  margin-left: 20rpx;
}

.exit-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.submit-btn {
  background-color: #fff;
  color: #1e4e8f;
}

.question-content {
  width: 690rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  box-sizing: border-box;
  margin: 20rpx auto;
}

.question-text {
  font-size: 34rpx;
  color: #333;
  line-height: 48rpx;
  margin-bottom: 20rpx;
}

.question-score {
  color: #666;
  font-size: 28rpx;
}

.divider {
  width: 630rpx;
  height: 2rpx;
  background-color: #a7a7a7;
  margin: 20rpx 0;
  font-size: 32rpx;
}

.options-list {
  width: 630rpx;
}

.option-item {
  width: 630rpx;
  min-height: 120rpx;
  margin-bottom: 30rpx;
  padding: 10rpx;
  border-radius: 10rpx;
}

.option-circle {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  background-color: #e2e2e2;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #060607;
  margin-right: 30rpx;
  margin-left: 20rpx;
  flex-shrink: 0;
}

.option-text {
  margin-top: 10rpx;
  font-size: 28rpx;
  color: #333;
  line-height: 44rpx;
  padding-left: 30rpx;
}

.option-item.selected .option-circle {
  background-color: #2873f9;
  color: #ffffff;
  border: 2rpx solid #2873f9;
}

.subjective-answer {
  width: 100%;
  margin-top: 20rpx;
}

.subjective-textarea {
  width: 100%;
  height: 300rpx;
  border: 1px solid #ccc;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
}

.bottom-nav {
  width: 750rpx;
  height: 120rpx;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
}

.bottom-nav-content {
  width: 750rpx;
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  box-sizing: border-box;
  border-bottom: 1rpx solid #eee;
}

.nav-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 32rpx;
  color: #333;
}

.answer-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 300rpx;
  height: 80rpx;
}

.indicator-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}

.indicator-text {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.do-button-group {
  padding: 7rpx;
  border-radius: 10rpx;
  border-color: white;
  border-style: solid;
  border-width: 4rpx;
}

// 底部占位，防止内容被底部导航栏遮挡
.bottom-placeholder {
  width: 100%;
  height: 150rpx;
}

.correct-answer {
  margin-top: 30rpx;
  padding: 20rpx;
  border-radius: 10rpx;
  color: #333;
  font-size: 30rpx;
}

.answer-label {
  font-weight: bold;
  margin-bottom: 10rpx;
  color: #2873f9;
}

.answer-content {
  line-height: 40rpx;
}

.show-answer-btn {
  margin: 30rpx 0 10rpx;
  padding: 15rpx 0;
  text-align: center;
  color: #2873f9;
  font-size: 28rpx;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 10rpx;
  border: 1rpx dashed #2873f9;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid #e0e0e0;
  padding-bottom: 20rpx;
}

.card-title {
  display: flex;
  align-items: center;
}

.card-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}

.card-title-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #2873f9;
}

.filter-buttons {
  display: flex;
  align-items: center;
}

.filter-btn {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 25rpx;
  margin-left: 20rpx;
  background-color: #f2f2f2;
  border-style: solid;
  border-width: 1px;
  border-color: #666;
  color: #666;
  font-size: 28rpx;
}

.filter-btn.active {
  background-color: #2873f9;
  color: #fff;
}

.question-grid {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
}

.question-item {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  color: #333;
  margin-left: 60rpx;
  margin-top: 40rpx;
  border-radius: 50%;
  background-color: #fff;
  border: 2rpx solid #e0e0e0;
}

.question-item.answered {
  background-color: #2873f9;
  color: #fff;
  border: 2rpx solid #2873f9;
}

.question-item.hidden {
  display: none;
}

.close-btn {
  color: red;
  width: 60rpx;
  height: 60rpx;
  background-color: #e8e8e8;
  border-radius: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
</style>
